
import fs from 'fs';
import path from 'path';
import dayjs from 'dayjs';

/** 启动项目时候 */
export function buildStartDictionary() {
    createDictionary(path.join(__dirname, '../../../../src/capabilityHooks'))
}

/** 创建能力字典 */
export function createDictionary(filePath: string) {
    filePath = filePath.replace(/\\/g, '/');
    try {
        if (!filePath.includes(`src/capabilityHooks`)) return;
        if (filePath.endsWith(`src/capabilityHooks/index.ts`)) return;

        console.log(`${dayjs().format('HH:mm:ss')} [vite-capability-manage] dictionary`)

        /** 能力路径 */
        const capabilityPath = path.join(__dirname, '../../../../src/capabilityHooks');
        const capabilitys = getDirectories(capabilityPath)
            .map(e => {
                const str = fs.readFileSync(path.join(e, 'index.tsx'), 'utf-8');
                return {
                    id: path.basename(e),
                    title: getProperty(str, 'title'),
                    tag: getProperty(str, 'tag'),
                    key: getProperty(str, 'key'),
                    description: getProperty(str, 'description'),
                    deprecated: getProperty(str, 'deprecated'),
                    private: getProperty(str, 'private'),
                }
            })

        const capabilityKeys = capabilitys.map(e => `"${e.id}"`).join(' | ');
        const mapStr = capabilitys.map(e => `
    ['${e.id}', {
        key: '${e.key}',
        id: '${e.id}',
        title: ${e.title ? `'${e.title}'` : null},
        tag: ${e.tag ? `'${e.tag}'` : null},
        description: ${e.description ? `'${e.description}'` : null},
        deprecated: ${e.deprecated ? `'${e.deprecated}'` : null},
        private: ${e.private ? `'${e.private}'` : null},
        load: async () => (await import('./${e.id}')).default
    }],
        `).join('')

        fs.writeFileSync(path.join(capabilityPath, '/index.ts'), `
// -----------------------------------------
// ------       请不要修改此文件        -------
// -----------------------------------------

export type CapabilityKeys = ${capabilityKeys || `''`};

export const dictionary = new Map<CapabilityKeys, any>([
${mapStr}
])`);
    } catch (error) {
        console.error(error)
    }
    console.log(`${dayjs().format('HH:mm:ss')} [vite-capability-manage] dictionary success`)
}

/** 获取属性 */
function getProperty(str: string, key: string): string | null {
    const match = str.match(new RegExp(`@${key}\\s+(.*?)\\s`, "s"));
    return match ? match[1] : null;
}

/** 获取路径下的目录 */
function getDirectories(source: string): string[] {
    return fs.readdirSync(source, { withFileTypes: true })
        .filter(dirent => dirent.isDirectory())
        .map(dirent => path.join(source, dirent.name));
}